/**
 * @param {number[][]} grid
 * @return {number}
 */
var orangesRotting = function(grid) {
    const queue = []
     const directions = [{ x: 0, y: 1 }, { x: 0, y: -1 }, { x: 1, y: 0 }, { x: -1, y: 0}]
     let m = grid.length, n = grid[0].length
     let freshNums = 0
     for(let i = 0; i < m; i++) {
         for(let j = 0; j < n; j++) {
             if(grid[i][j] === 2) {
                 queue.push([i, j])
             } else if(grid[i][j] === 1) {
                 freshNums++
             }
         }
     }
     const isValid = (x, y) => {
         return x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1
     }
     let ans = 0
     while(queue.length > 0 && freshNums > 0) {
         let len = queue.length
         ans++
         for(let i = 0; i < len; i++) {
             let tmp = queue.shift()
             for(let j = 0; j < 4; j++) {
                 let x1 = tmp[0] + directions[j].x
                 let y1 = tmp[1] + directions[j].y
                 if(isValid(x1,y1)) {
                     // 被感染
                     freshNums--
                     grid[x1][y1] = 2
                     queue.push([x1, y1])
                 }
             }
         }
     }
     if(freshNums > 0) return - 1
     return ans
 };